Page({
  data: {
    currentFood: '',
    currentIndex: 0,
    isAnimating: false,
    countdown: 3,
    foodList: [
      '红烧肉',
      '蹄花汤',
      '宫保鸡丁',
      '鱼香肉丝',
      '麻婆豆腐',
      '回锅肉',
      '水煮鱼',
      '夫妻肺片'
    ]
  },

  onLoad() {
    this.startCountdown();
  },

  startCountdown() {
    this.setData({
      timer: setInterval(() => {
        if(this.data.countdown > 0) {
          this.setData({countdown: this.data.countdown - 1})
        } else {
          clearInterval(this.data.timer)
          this.selectFood()
        }
      }, 1000)
    })
  },

  selectFood() {
    if (this.data.isAnimating) return;
    
    this.setData({ 
      isAnimating: true,
      countdown: 3,
      currentIndex: 0 
    });

    const blacklist = wx.getStorageSync('blacklist') || [];
    const availableFoods = this.data.foodList.filter(
      food => !blacklist.includes(food)
    );

    console.log('可用菜品列表:', availableFoods);
    console.log('黑名单数据:', blacklist);
    this.setData({ availableCount: availableFoods.length });
    if (availableFoods.length === 0) {
      wx.showToast({ title: '没有可用菜品', icon: 'none' });
      return;
    }

    this.animationTimer = setInterval(() => {
      const newIndex = Math.floor(Math.random() * availableFoods.length);
      this.setData({ currentIndex: newIndex });
    }, 200);

    setTimeout(() => {
      clearInterval(this.animationTimer);
      const finalIndex = Math.floor(Math.random() * availableFoods.length);
      this.setData({
        isAnimating: false,
        currentFood: availableFoods[finalIndex]
      });
    }, 3000);
  },

  saveToFavorites() {
    if(this.data.currentFood) {
      const favorites = wx.getStorageSync('favorites') || [];
      wx.setStorageSync('favorites', [...favorites, this.data.currentFood]);
      wx.showToast({ title: '收藏成功' });
    }
  }
})